package log4j.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.demo.persistencia.generica.dao.GenericDao;
import com.demo.persistencia.generica.modelo.Log4jdata;
import com.demo.persistencia.generica.util.Busqueda;
import com.demo.persistencia.generica.util.HibernateUtil;

@ManagedBean(name = "log4MB")
@SessionScoped
public class Log4jManager implements Serializable{

	private static Logger log = Logger.getLogger(Log4jManager.class);
	private static final long serialVersionUID = 1L;

	private List<Log4jdata> lstLogger = null;
	private List<SelectItem> lstLevel;
	private LoggerFiltroDTO slogfilter;
	private Integer iCantLogger;
	private HibernateUtil hUtil;
	private StreamedContent file;
    private String sPath; //C:/resources/logConsola.txt
    
    
	public Log4jManager() {
		log.info("Estoy en el constructor de Log4jManager");
		hUtil = new HibernateUtil();
		hUtil.IniciarContextoSpring();
		lstLogger = new ArrayList<Log4jdata>();
		comboboxLevel();
		slogfilter = new LoggerFiltroDTO();
		
	}

	public void comboboxLevel() {

		lstLevel = new ArrayList<SelectItem>();
		lstLevel.add(new SelectItem(Utilitarios.TRACE, "TRACE"));
		lstLevel.add(new SelectItem(Utilitarios.DEBUG, "DEBUG"));
		lstLevel.add(new SelectItem(Utilitarios.INFO, "INFO"));
		lstLevel.add(new SelectItem(Utilitarios.WARN, "WARN"));
		lstLevel.add(new SelectItem(Utilitarios.ERROR, "ERROR"));
		lstLevel.add(new SelectItem(Utilitarios.FATAL, "FATAL"));

	}
	
  
	public void filtrarLogger() {
		
		Utilitarios.putObjectInSession("lstLogger", new ArrayList<Log4jdata>());
		
		log.info("idCbolevel: " + slogfilter.getsLevel());
		log.info("sThread: " + slogfilter.getsThread());
		log.info("sLogger: " + slogfilter.getsLogger());
		log.info("sNDC(): " + slogfilter.getsNDC());
		log.info("sMessage(): " + slogfilter.getsMessage());
		log.info("sFInicio(): " + slogfilter.getsFInicio());
		log.info("sFFin(): " + slogfilter.getsFFin());
		
		try {
			
		GenericDao<Log4jdata, LoggerFiltroDTO> entidadDAO = (GenericDao<Log4jdata, LoggerFiltroDTO>)hUtil.getContextoSpring().getBean("genericoDao");
        if(entidadDAO!=null){
        	
      
        
		Busqueda filtro = Busqueda.forClass(Log4jdata.class);
			     filtro.addOrder(Order.asc("id"))
		        .add(Expression.like("thead", "%" + slogfilter.getsThread()+ "%"))
				.add(Expression.like("mensaje", "%" + slogfilter.getsLogger()+ "%"))
				.add(Expression.like("clase", "%" + slogfilter.getsMessage()+ "%"))
				.add(Expression.like("prioridad", slogfilter.getsLevel() + "%"));

		if (slogfilter.getsFInicio() != null) {
			filtro.add(Expression.ge("fecha", slogfilter.getsFInicio()));
		}
		if (slogfilter.getsFFin() != null) {
			filtro.add(Expression.le("fecha", slogfilter.getsFFin()));
		}

		int i = 0;
		lstLogger = entidadDAO.buscarDinamico(filtro);
		for (Log4jdata log : lstLogger) {
			i++;
			log.setItem(i);
		}
		iCantLogger = lstLogger.size();
		System.out.println("iCantLogger : " + iCantLogger);
		//Poner la lista del Reporte en Session
		Utilitarios.putObjectInSession("lstLogger", lstLogger);
        }//Fin del If
        else{
        	log.info("El objeto es Nullo .... ");
        	
        	
        }
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	public void limpiar() {
		log.info("En el metodo limpiar()");
		slogfilter = new LoggerFiltroDTO();
		iCantLogger = 0;
	}
	
    public void dowloadLogger(){
    	  log.info("dowloadLogger   ");
    	 
    	  try { 
    		 
    		   if(sPath!=null && sPath!=""){
    			 log.info("entro al if ");
    			File fl = new File(sPath);

              if (fl.exists()) {
                  InputStream stream = new FileInputStream(fl);
             	 log.info("si existe");
                  file = new DefaultStreamedContent(stream, "application/txt", "downloaded_file.txt");
              }
    		   }else{
    			 log.info("entro al else ");
    			 Utilitarios.mensajeInfo("Info :", "Ingrese la ruta a descargar.");
    		   }
    	
              
          } catch (FileNotFoundException e) {
          	e.printStackTrace();

          }catch (Exception e) {
  			e.printStackTrace();
  		}
      }
      

	public List<SelectItem> getLstLevel() {
		return lstLevel;
	}

	public void setLstLevel(List<SelectItem> lstLevel) {
		this.lstLevel = lstLevel;
	}

	public List<Log4jdata> getLstLogger() {
		return lstLogger;
	}

	public void setLstLogger(List<Log4jdata> lstLogger) {
		this.lstLogger = lstLogger;
	}

	public LoggerFiltroDTO getSlogfilter() {
		return slogfilter;
	}

	public void setSlogfilter(LoggerFiltroDTO slogfilter) {
		this.slogfilter = slogfilter;
	}

	public Integer getiCantLogger() {
		return iCantLogger;
	}

	public void setiCantLogger(Integer iCantLogger) {
		this.iCantLogger = iCantLogger;
	}


	public String getsPath() {
		return sPath;
	}

	public void setsPath(String sPath) {
		this.sPath = sPath;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

}
